<template>
  <draw-component
    :drawer-visible="state.show"
    size="410px"
    title="新增字典"
    @close-drawer="handleClose"
    @save-drawer="handleSubmit"
  >
    <el-form
      ref="formRef"
      :model="state.formData"
      :rules="state.formRules"
      label-width="auto"
      class="my-form-box2"
    >
      <el-form-item
        label="字典编码:"
        prop="dictionaryCode"
        :rules="
          state.isEdit
            ? []
            : [
                { required: true, message: '请输入字典编码', trigger: 'blur' },
                { validator: validCode },
                { validator: validateCode }
              ]
        "
      >
        <el-input
          v-model="state.formData.dictionaryCode"
          :disabled="state.isEdit ? true : false"
          placeholder="请输入字典编码"
        ></el-input>
      </el-form-item>
      <el-form-item label="字典名称:" prop="dictionaryName">
        <el-input v-model="state.formData.dictionaryName" placeholder="请输入字典名称"></el-input>
      </el-form-item>
      <el-form-item label="字典值:" prop="dictionaryValue">
        <el-input v-model="state.formData.dictionaryValue" placeholder="请输入字典值"></el-input>
      </el-form-item>
      <el-form-item label="使用状态:" prop="status">
        <el-select v-model="state.formData.status" placeholder="请选择状态">
          <el-option
            v-for="item in dicStatusDics"
            :key="item.code"
            :label="`${item.code} - ${item.name}`"
            :value="item.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="(state.isEdit && state.parentId == '0') || !state.currentId"
        label="父级编号前缀启用:"
        prop="parentIdPrefix"
      >
        <el-select v-model="state.formData.parentIdPrefix" placeholder="请选择父级编号前缀启用">
          <el-option
            v-for="item in parentIdPrefixDics"
            :key="item.code"
            :label="`${item.code} - ${item.name}`"
            :value="item.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注:" prop="remark">
        <el-input v-model="state.formData.remark" type="textarea" placeholder="请输入备注"></el-input>
      </el-form-item>
    </el-form>
  </draw-component>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import { dicStatusDics, parentIdPrefixDics } from '@/hooks/dicsData'
import { validCode } from '@/utils/validate'
import { addParentSubmit, editParentSubmit, addSubmit, editSubmit, dicNameExist, dicCodeExist } from '../api'
import { useProxy } from '@/utils/proxy'
const validateName = async (rule: any, value: any, callback: any) => {
  if (!value) return callback()
  const { data } = await dicNameExist<boolean>({
    dictionaryName: value,
    parentDictionaryCode: state.isEdit ? state.parentId : state.currentId || '0',
    id: state.currentId || null
  })
  if (!data) {
    callback(new Error('字典名称重复'))
  } else {
    callback()
  }
}
const validateCode = async (rule: any, value: any, callback: any) => {
  if (!value) return callback()
  const { data } = await dicCodeExist<boolean>({
    dictionaryCode: value,
    parentDictionaryCode: state.isEdit ? state.parentId : state.currentId || '0',
    id: state.currentId || null
  })
  if (!data) {
    callback(new Error('字典编码重复'))
  } else {
    callback()
  }
}
const emit = defineEmits(['handleAdded'])
const { proxy } = useProxy()
const formRef = ref<FormInstance>()
const state = reactive({
  currentId: '',
  parentId: '',
  level: '',
  isEdit: false,
  show: false,
  isSubmiting: false,
  formData: {
    dictionaryCode: '',
    dictionaryName: '',
    dictionaryValue: '',
    status: '1',
    parentIdPrefix: '0',
    remark: ''
  },
  formRules: {
    dictionaryName: [
      { required: true, message: '请输入字典名称', trigger: 'blur' },
      { validator: validateName, trigger: 'blur' }
    ]
  } as FormRules
})

// 关闭回调
const handleClose = () => {
  state.show = false
  state.currentId = ''
  state.level = ''
  state.parentId = ''
  state.formData = {
    dictionaryCode: '',
    dictionaryName: '',
    dictionaryValue: '',
    status: '1',
    parentIdPrefix: '0',
    remark: ''
  }
}
// 获取详情
const getDetail = (row: any) => {
  let form = {} as any
  Object.keys(state.formData).forEach((item, index) => {
    form[item] = row[item] ?? ''
  })
  state.formData = form
}
// 保存
const handleSubmit = async () => {
  await formRef.value?.validate(async (valid) => {
    if (valid) {
      if (state.isSubmiting) return
      state.isSubmiting = true
      const params = { ...state.formData } as any
      if ((state.isEdit && state.parentId != '0') || (!state.isEdit && state.currentId)) {
        delete params.parentIdPrefix
      }
      if (state.isEdit) {
        state.parentId == '0'
          ? editParentSubmit(state.currentId, params)
              .then(() => {
                proxy.$message.msgSuccess('编辑成功')
                state.isSubmiting = false
                handleClose()
                emit('handleAdded')
              })
              .catch(() => {
                state.isSubmiting = false
              })
          : editSubmit(state.currentId, { ...params, parentDictionaryCode: state.parentId })
              .then(() => {
                proxy.$message.msgSuccess('编辑成功')
                state.isSubmiting = false
                handleClose()
                emit('handleAdded')
              })
              .catch(() => {
                state.isSubmiting = false
              })
      } else {
        !state.currentId
          ? addParentSubmit(params)
              .then(() => {
                proxy.$message.msgSuccess('新增成功')
                state.isSubmiting = false
                handleClose()
                emit('handleAdded')
              })
              .catch(() => {
                state.isSubmiting = false
              })
          : addSubmit(state.currentId, { ...params, level: Number(state.level) + 1 })
              .then(() => {
                proxy.$message.msgSuccess('新增成功')
                state.isSubmiting = false
                handleClose()
                emit('handleAdded')
              })
              .catch(() => {
                state.isSubmiting = false
              })
      }
    }
  })
}
defineExpose({ state, getDetail })
</script>

<style lang="scss" scoped></style>
